﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

namespace QuaManSys.OuterInfo
{
    public partial class OuterInfoDistribute : System.Web.UI.Page
    {

        protected void Page_Load(object sender, EventArgs e)
        {
            lblQuaInfoProNo.Text = Request.QueryString["id"]; //修改为查询字符串
            fdbktime.Attributes.Add("ReadOnly", "True");
            lblCusRT.Attributes.Add("ReadOnly", "True");
            txtProDL.Attributes.Add("ReadOnly", "True");
            txtKeyWords.Attributes.Add("ReadOnly", "True");

            if (!IsPostBack)
            {
                initddlProNo();
                initResponDept();
                initRelatedDept();

                initQuaInfoTextBox();
                initDepartTextBox();
                initFeedBackTextBox();

            }
        }
        #region display
        /// <summary>
        /// 把外部质量信息表中的数据显示出来
        /// </summary>
        private void initQuaInfoTextBox()
        {
            using (QuaManSysEntities context = new QuaManSysEntities())
            {
                var qualityInfo = from c in context.OuterQualityInfo
                                  where c.qualityInfoId == lblQuaInfoProNo.Text
                                  select c;
                txtInfoCla.Text = qualityInfo.Single().informationSource;
                txtImpLev.Text = qualityInfo.Single().levelOfImportance;
                ddlProNo.Text = qualityInfo.Single().projectNo;
                txtlblMacTyp.Text = CommonInitFunctions.getMachModelNo(ddlProNo.Text);
                txtlblMacNo.Text = CommonInitFunctions.getMachineNo(ddlProNo.Text);
                txtComponent.Text = qualityInfo.Single().components;
                txtFaiTyp.Text = qualityInfo.Single().faultType;
                txtManufac.Text = qualityInfo.Single().producer;
                txtPjCls.Text = qualityInfo.Single().projectCategory;
                txtPjNam.Text = qualityInfo.Single().name;
                txtInfoDsc.Text = qualityInfo.Single().description;
                InfoCls.SelectedIndex = Convert.ToInt16(qualityInfo.Single().informationCategory);
                txtReqAdv.Text = qualityInfo.Single().recommendedTreatPlan;
                txtReqRsl.Text = qualityInfo.Single().processingResults;
                txtProCmm.Text = qualityInfo.Single().processingAssess;
                txtProDL.Text = qualityInfo.Single().deadline.ToString().Substring(0, 10);

            }
        }

        /// <summary>
        /// 把责任部门和关注部门显示出来
        /// </summary>
        private void initDepartTextBox()
        {
            using (QuaManSysEntities context = new QuaManSysEntities())
            {
                var dept = from c in context.OuterResponsibleDepart
                           where c.qualityInfoId == lblQuaInfoProNo.Text
                           select c;
                string deptString = "";
                foreach(var item in dept)
                {
                    if (item.isResponDepart == 0)
                    {
                        if (deptString == "") deptString += item.department;
                        else deptString += "|" + item.department;
                    }
                    else
                    {
                        ResponDept.Text = item.department;
                    }
                }
                txtKeyWords.Text = deptString;
            }
        }

        /// <summary>
        /// 显示反馈表中的数据
        /// </summary>
        private void initFeedBackTextBox()
        {
            using (QuaManSysEntities context = new QuaManSysEntities())
            {
                var fbset = from c in context.OuterQualityInfoFeedback
                            where c.qualityInfoId == lblQuaInfoProNo.Text
                            select c;
                lblFdCom.Text = fbset.Single().feedbackUnit;
                txtFdPer.Text = fbset.Single().feedbackName;
                fdbktime.Text = fbset.Single().feedbackTime.ToString().Substring(0,10);
                ProcssComd.SelectedIndex = Convert.ToInt16(fbset.Single().processingDemands);
                lblCusCo.Text = fbset.Single().customerCompany;
                lblRelCo.Text = fbset.Single().relatedParty;
                lblCusNam.Text = fbset.Single().customerName;
                lblCusRol.Text = fbset.Single().customerRole;
                lblCusTel.Text = fbset.Single().customerPhone;
                lblCusRT.Text = fbset.Single().customerReqCloTime.ToString().Substring(0, 10);
                CareLevel.SelectedIndex = Convert.ToInt16(fbset.Single().customerAttitude);
                TextBox4.Text = fbset.Single().cusomerOtherInfo;
                TextBox2.Text = fbset.Single().qualityInfoDes;
                TextBox3.Text = fbset.Single().solutionProposal;
                string s = fbset.Single().subsequentRequest;
                if (s.Length == 1)
                {
                    CustmReq.SelectedIndex = Convert.ToInt16(s);
                }
                else
                {
                    CustmReq.SelectedIndex = 3;
                    instruction.Text = s.Substring(2);
                }

                            
            }
        }
        #endregion
        protected void submit_Click(object sender, EventArgs e)
        {
            if (isValidate())
            {
                insertQualityInfo();
                insertQuaFeedback();
                insertResponsDept();
                Response.Redirect("SubmitSuccess.aspx");
            }
            else
            {
                Response.Redirect("OuterInfoRegist.aspx");
            }
        }

        protected void ddlProNo_SelectedIndexChanged(object sender, EventArgs e)
        {
            string projNo = ddlProNo.Text;
            txtlblMacTyp.Text = CommonInitFunctions.getMachModelNo(projNo);
            txtlblMacNo.Text = CommonInitFunctions.getMachineNo(projNo);
        }

        /*
         * multiView的下一步
         */
        protected void nextstep_Click(object sender, EventArgs e)
        {
            MultiView1.ActiveViewIndex = 1;
        }

        /*
         * multiView的上一步
         */
        protected void prestep_Click(object sender, EventArgs e)
        {
            MultiView1.ActiveViewIndex = 0;
        }

        #region

        /// <summary>
        /// 初始化工程编号下拉框
        /// </summary>
        private void initddlProNo()
        {
            using (var context = new QuaManSysEntities())
            {
                try
                {
                    ddlProNo.Items.Clear();
                    int count = 0;
                    foreach (var item in context.Tab_ProjectNo)
                    {
                        ListItem li = new ListItem(item.projectNo);
                        ddlProNo.Items.Insert(count++, li);
                    }
                    txtlblMacTyp.Text = CommonInitFunctions.getMachModelNo(ddlProNo.Items[0].Text);
                    txtlblMacNo.Text = CommonInitFunctions.getMachineNo(ddlProNo.Items[0].Text);
                }
                catch (EntitySqlException ex)
                {
                    Response.Write("<script>alert('" + ex.ToString() + "')</script>");
                }
            }
        }
        
        
          
        /// <summary>
        /// 初始化责任部门下拉框选项
        /// </summary>
        private void initResponDept()
        {
            using (var context = new QuaManSysEntities())
            {
                try
                {
                    ResponDept.Items.Clear();
                    int count = 0;
                    foreach (var item in context.Tab_Department)
                    {
                        ListItem li = new ListItem(item.department);
                        ResponDept.Items.Insert(count++, li);
                    }
                }
                catch (EntitySqlException ex)
                {
                    Response.Write("<script>alert('" + ex.ToString() + "')</script>");
                }
            }
        }

        /// <summary>
        /// 初始化关注部门复选框选项
        /// </summary>
        private void initRelatedDept()
        {
            using (var context = new QuaManSysEntities())
            {
                try
                {
                    cblKeyWords.Items.Clear();
                    int count = 0;
                    foreach (var item in context.Tab_Department)
                    {
                        ListItem li = new ListItem(item.department);
                        cblKeyWords.Items.Insert(count++, li);
                    }
                }
                catch (EntitySqlException ex)
                {
                    Response.Write("<script>alert('" + ex.ToString() + "')</script>");
                }
            }
        }

        /// <summary>
        /// 把质量信息修改后写入数据库
        /// </summary>
        private void insertQualityInfo()
        {
            using (QuaManSysEntities context = new QuaManSysEntities())
            {
                string infoCategory = InfoCls.SelectedValue;

                OuterQualityInfo outInfo = new OuterQualityInfo
                {
                    qualityInfoId = lblQuaInfoProNo.Text,
                    projectNo = ddlProNo.Text,
                    components = txtComponent.Text,
                    producer = txtManufac.Text,
                    faultType = txtFaiTyp.Text,
                    projectCategory = txtPjCls.Text,
                    name = txtPjNam.Text,
                    deadline = Convert.ToDateTime(txtProDL.Text),
                    informationCategory = infoCategory,
                    informationSource = txtInfoCla.Text,
                    levelOfImportance = txtImpLev.Text,
                    description = txtInfoDsc.Text,
                    recommendedTreatPlan = txtReqAdv.Text,
                    processingStatus = "处理",
                    processingResults = txtReqRsl.Text,
                    processingAssess = txtProCmm.Text
                };
                context.OuterQualityInfo.Attach(outInfo);
                context.Entry(outInfo).State = EntityState.Modified;
                context.SaveChanges();
            }
        }

        /// <summary>
        /// 将反馈表修改后写入数据库
        /// </summary>
        private void insertQuaFeedback()
        {
            using (QuaManSysEntities context = new QuaManSysEntities())
            {
                string subsquReq = CustmReq.SelectedItem.Text;
                if (CustmReq.SelectedIndex == 3)
                    subsquReq += "|" + instruction.Text;
                OuterQualityInfoFeedback OutQuaFdbck = new OuterQualityInfoFeedback
                {
                    qualityInfoId = lblQuaInfoProNo.Text,
                    feedbackUnit = lblFdCom.Text,
                    feedbackName = txtFdPer.Text,
                    feedbackTime = Convert.ToDateTime(fdbktime.Text),
                    customerCompany = lblCusCo.Text,
                    relatedParty = lblRelCo.Text,
                    customerName = lblCusNam.Text,
                    customerRole = lblCusRol.Text,
                    customerPhone = lblCusTel.Text,
                    customerReqCloTime = Convert.ToDateTime(lblCusRT.Text),
                    customerAttitude = CareLevel.SelectedItem.Text,
                    cusomerOtherInfo = TextBox4.Text,
                    qualityInfoDes = TextBox2.Text,
                    solutionProposal = TextBox3.Text,
                    subsequentRequest = subsquReq,
                    processingDemands = ProcssComd.SelectedItem.Text
                };

                context.OuterQualityInfoFeedback.Attach(OutQuaFdbck);
                context.Entry(OutQuaFdbck).State = EntityState.Modified;
                context.SaveChanges();

            }
        }

        /// <summary>
        /// 将责任部门修改后写入数据库
        /// </summary>
        private void insertResponsDept()
        {
            using (QuaManSysEntities context = new QuaManSysEntities())
            {
              
                OuterResponsibleDepart dep = new OuterResponsibleDepart();
                dep.qualityInfoId = lblQuaInfoProNo.Text;
                context.OuterResponsibleDepart.Attach(dep);
                context.OuterResponsibleDepart.Remove(dep);
                context.SaveChanges();              //TODO:to be fixed 

              /*  OuterResponsibleDepart respons = new OuterResponsibleDepart
                {
                    qualityInfoId = lblQuaInfoProNo.Text,
                    isResponDepart = 1,
                    department = ResponDept.Text
                };

                context.OuterResponsibleDepart.Add(respons);
                context.SaveChanges();

                string focString = txtKeyWords.Text;
                string[] focDept = focString.Split('|');

                for (int i = 0; i < focDept.Length; i++)
                {
                    OuterResponsibleDepart focusDept = new OuterResponsibleDepart
                    {
                        qualityInfoId = lblQuaInfoProNo.Text,
                        isResponDepart = 0,
                        department = focDept[i]
                    };
                    context.OuterResponsibleDepart.Add(focusDept);
                    context.SaveChanges();
                }*/

            }
        }
        #endregion

        bool isValidate()
        {
            if (fdbktime.Text == "") return false;
            if (lblCusRT.Text == "") return false;
            if (txtProDL.Text == "") return false;
            return true;
        }

    }
}